﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MetadataDocumentationGenerator.Helpers;

namespace MetadataDocumentationGenerator.Dialog
{
    public partial class EntityLoad : Form
    {
        private readonly List<Microsoft.Xrm.Sdk.Metadata.EntityMetadata> _entityList;
        private readonly List<EntityItem> _list;
        private readonly BackgroundWorker _worker;
        private readonly Microsoft.Xrm.Sdk.IOrganizationService _service;

        public EntityLoad()
        {
            InitializeComponent();
        }

        public EntityLoad(List<Microsoft.Xrm.Sdk.Metadata.EntityMetadata> entityList, List<EntityItem> list, Microsoft.Xrm.Sdk.IOrganizationService service)
        {
            _entityList = entityList;
            _list = list;
            _service = service;

            _worker = new BackgroundWorker();
            _worker.DoWork += new DoWorkEventHandler(WorkerDoWork);

            InitializeComponent();
        }

        void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;

            progressBar.InvokeIfRequired(a => { progressBar.Maximum = _list.Count; });
            

            foreach (var entityItem in _list)
            {
                var emd = _entityList.Single(f => f.LogicalName == entityItem.Name);
                
                i++;
                lblEntity.InvokeIfRequired(a =>
                {
                    lblEntity.Text = "Entity " + i.ToString(CultureInfo.InvariantCulture) + "/" + _list.Count.ToString(CultureInfo.InvariantCulture) + " : " + emd.LogicalName;
                    progressBar.Value = i;
                });
                
                if (emd.Attributes == null)
                {
                    var completeEmd = MetadataHelper.RetrieveEntity(emd.LogicalName, _service);
                    _entityList.Remove(emd);
                    _entityList.Add(completeEmd);
                }
            }
            this.InvokeIfRequired(a=> Close());
        }

        private void EntityLoad_Load(object sender, EventArgs e)
        {
            _worker.RunWorkerAsync();
        }
    }
}
